System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

56% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Day 7: Social Graph & Networking
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Day 8: Collaboration Tools
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design a Collaborative Whiteboard (Miro)
Image

Here is the step-by-step system design for a Collaborative Whiteboard (like Miro).

1. Problem Definition and Scope

We are designing a real-time collaborative whiteboard where multiple users can draw, write, and organize items on an "infinite canvas" simultaneously. The system must synchronize changes instantly so all users see the same state, providing a seamless multiplayer experience.

  • Main User Groups: Creators (who start the session) and Collaborators (who join to edit or view).

  • Main Actions: Drawing shapes, adding sticky notes, moving objects, and seeing other users' mouse cursors in real-time.

  • Scope: We will focus on the real-time collaboration engine (synchronizing vector objects and cursors) and board persistence.

  • Out of Scope: We will not cover video/audio conferencing, screen sharing, complex enterprise permissions (SSO), or third-party integrations (Jira/Slack).

Image

2. Clarify functional requirements

Must Have:

  • Board Management: Users can create a board and share it via a unique URL.

  • Real-time Sync: Actions (like dragging a shape) are reflected instantly on other users' screens.

  • Object Management: Support for shapes (rectangles, circles), sticky notes, and freehand drawing.

  • Transformations: Users can move, resize, rotate, and change colors of objects.

  • Presence: Users can see the live cursors and names of other active users.

  • Persistence: The board state is saved automatically and persists after the session ends.

Nice to Have:

  • Undo/Redo: Support for reversing recent actions in the current session.

  • Image Upload: Users can upload images to the canvas.

  • Viewport Awareness: Optimization to only load/sync objects visible on the user's screen.

Image

3. Clarify non-functional requirements

  • Target Users: 10 Million Daily Active Users (DAU).

  • Concurrency: Average 10 users per board. Peak "Town Hall" sessions may have 500+ active users.

  • Latency: Extremely low (< 100ms). The collaboration must feel "live."

  • Read vs. Write: This is a write-heavy system during active sessions. Every mouse drag generates a stream of data events.

  • Availability: High (99.9%). Connection drops should be handled gracefully with auto-reconnect.

  • Consistency: Strong eventual consistency. If User A moves a box to the left and User B moves it to the right, the system must resolve this so everyone sees the box in the same final spot.

Image

4. Back of the envelope estimates

  • Traffic Estimate:
    • 10M DAU.
    • Assume 5% concurrent usage at peak = 500,000 concurrent users.
    • Activity: A user drawing or dragging generates frequent events. We throttle this to 10 events/second per active user.
    • Peak Ingress: 500,000 users * 10 events/sec = 5 Million events/second.
    • Note: This is too high for a standard database. We must aggregate data in memory before saving.
  • Bandwidth:
    • Average message (JSON delta): ~100 bytes.
    • Ingress: 5M * 100 bytes = 500 MB/sec.
    • Egress (Fan-out): If 1 user draws and 5 watch, egress is 5x ingress = 2.5 GB/sec.
  • Storage:
    • We store vector instructions (coordinates), not pixels.
    • Average board size (snapshot): 500 KB.
    • 1 Million new boards/day * 500 KB = 500 GB / day.
    • This is manageable with standard object storage or a document database.
Image

5. API design

We need a hybrid approach: HTTP for board management and WebSockets for the live interactive session.

HTTP API (Management)

  • POST /v1/boards
    • Response: { "board_id": "b_123", "title": "Untitled", "created_at": "..." }
  • GET /v1/boards/{board_id}/snapshot
    • Response: Returns the board metadata and the initial list of objects (shapes, notes).
  • POST /v1/boards/{board_id}/assets

WebSocket API (Real-time Session)

  • Connect: ws://api.miroclone.com/v1/boards/{board_id}/ws
  • Client -> Server Messages:
    • JOIN: { "token": "..." }
    • OP_UPDATE: { "id": "shape_1", "type": "RECT", "data": { "x": 100, "y": 200 } }
    • OP_CURSOR: { "x": 50, "y": 80 }
  • Server -> Client Messages:
    • BROADCAST_OP: { "user_id": "u1", "id": "shape_1", "data": { "x": 100, "y": 200 } }
    • BROADCAST_CURSOR: { "user_id": "u1", "x": 50, "y": 80 }

6. High level architecture

We will use a Stateful Architecture for the real-time engine. Keeping the board state in memory on the server allows for lower latency and better conflict resolution compared to a purely stateless architecture.

  1. Client: The web browser running the whiteboard app (React/Canvas). It handles rendering and "Optimistic UI" updates.

  2. Load Balancer: Distributes connections. Crucially, it uses Sticky Sessions (based on board_id hash) to ensure all users editing "Board A" are routed to the same WebSocket server.

  3. WebSocket Gateway (Stateful Service):

    • Holds the active board state in memory (RAM).
    • Acts as the "Source of Truth" for the live session.
    • Receives updates, resolves conflicts, and broadcasts changes to other connected users immediately.
  4. Message Queue (Kafka):

    • The WebSocket server pushes confirmed changes here asynchronously.
    • This decouples the high-speed live session from the slower database.
  5. Database Writer (Worker): Reads from Kafka, batches updates (e.g., groups 50 moves of "Shape A" into one final position), and writes to the DB.

  6. Database (MongoDB): Stores the persistent state of boards and objects.

  7. Object Storage (S3): Stores uploaded images and large board snapshots.

Image

7. Data model

We will use a NoSQL Document Store (MongoDB).

Whiteboard data is unstructured and hierarchical. A "Board" contains a list of "Objects," and each object (square, line, text) has different properties. JSON documents fit this perfectly.

Collection: Boards

  • _id: UUID
  • owner_id: UUID
  • title: String
  • created_at: Timestamp

Collection: BoardObjects

  • _id: UUID
  • board_id: UUID (Indexed, Sharding Key)
  • type: String ("rect", "text", "path")
  • data: JSON Object (x, y, w, h, color, text, points[])
  • z_index: Integer (Layer order)
  • last_modified_by: UUID

Media Storage:

We do not store binary image data in MongoDB. We store the url pointing to S3 (e.g., {"type": "image", "src": "https://s3..."}).

8. Core flows end to end

We will detail the "Real-time Shape Movement" flow. This is the heart of the system.

Step 1: Local Optimistic Update (Client A)

  • User A clicks a sticky note and drags it 100 pixels to the right.

  • Client A does not wait for the server. It immediately renders the note at the new position. This makes the UI feel "instant" (Zero Latency).

Step 2: Throttling and Sending (Client A)

  • The mouse moves 60 times a second. Sending 60 network packets is wasteful.

  • Client A throttles the events. It collects moves every 50ms (20 times/sec).

  • It sends one WebSocket message: OP_UPDATE { id: "note_1", x: 200, y: 300 }.

Step 3: Processing (WebSocket Server)

  • The Load Balancer routes the message to the specific WebSocket Server responsible for this board (via Sticky Session).

  • The server updates its In-Memory Board State (RAM). This is extremely fast (nanoseconds).

  • Conflict Resolution: If User C also tried to move "note_1" at the same time, the server decides who wins (typically "Last Write Wins" based on server arrival time).

Step 4: Broadcasting (WebSocket Server)

  • The server looks up its list of connected sockets for this board.

  • It finds User B's connection.

  • It sends the JSON payload BROADCAST_OP { id: "note_1", x: 200, y: 300 } to User B.

Step 5: Remote Render (Client B)

  • User B's browser receives the message.

  • It uses the new coordinates to animate "note_1" moving to the new spot.

  • Total time from A moving to B seeing it: ~50ms to 100ms.

Step 6: Async Persistence (The "Save" Step)

  • We cannot update the database 20 times a second per user.

  • The WebSocket Server pushes the change to a Kafka Topic.

  • A background Writer Worker picks up the message. It debounces the updates (waits a few seconds to see if more moves come in).

  • It creates a single database update: db.BoardObjects.update({_id: "note_1"}, {$set: {x: 200, y: 300}}).

Image

9. Caching and read performance

  • In-Memory "Hot" State (Level 1 Cache):
    • The primary cache is the memory of the WebSocket server itself.
    • When a new user joins a board that is already active, the server sends the state directly from RAM, avoiding a database hit entirely.
  • Redis Cache (Routing Directory):
    • We use Redis to map board_id -> server_ip.
    • This helps the routing layer know which server is currently hosting "Board X" so it can route new users there.
  • Client Caching:
    • The browser stores the board state in IndexedDB. If the user refreshes, we load from local storage first, then ask the server for "Changes since timestamp T".

10. Storage, indexing and media

  • Primary Database (MongoDB):
    • Sharding: We shard the BoardObjects collection by board_id. This ensures that all objects for "Board 1" live on the same database shard, making the query "Load Board 1" extremely efficient.
    • Indexes: (board_id, z_index). This helps us load objects in the correct visual order (background to foreground).
  • Media Storage (S3 + CDN):
    • When a user drags an image onto the canvas, the client uploads it directly to S3 (using a Presigned URL generated by the API).
    • Once uploaded, the client sends a WebSocket message saying "I added an image at this URL."
    • Other clients download the image from a CDN (CloudFront), ensuring fast loading globally.

11. Scaling strategies

  • Stateful Server Scaling:
    • Since one server holds the state for a board, we can scale by adding more servers.
    • Server 1 handles Board A, Server 2 handles Board B.
  • Handling "Mega Boards" (The Fan-out Bottleneck):
    • If 1,000 users are on one board, a single server might overload trying to send 1,000 messages for every mouse move.
    • Strategy: Viewport Culling (Spatial Subscriptions).
    • The server divides the infinite canvas into "grid tiles."
    • Clients tell the server: "I am looking at Tile (0,0)."
    • If User A draws in Tile (0,0), the server only sends updates to other users looking at that tile. Users looking at a different part of the board receive nothing. This drastically reduces bandwidth.

12. Reliability, failure handling and backpressure

  • Server Crash (Failover):
    • If the WebSocket Server hosting "Board A" crashes, all users disconnect.
    • Clients auto-reconnect. The Load Balancer routes them to a new, healthy server.
    • The new server reads the last persisted state from MongoDB to rebuild the memory state.
  • Backpressure:
    • If a user has a slow internet connection, messages will pile up in their outgoing queue on the server.
    • The server can detect this and switch to "Snapshot Mode"—dropping intermediate movement updates and only sending the final position of objects.

13. Security, privacy and abuse

  • Authentication:
    • Standard JWT (JSON Web Token). The client sends the token in the WebSocket handshake request.
  • Authorization:
    • Before allowing a socket to subscribe to a board channel, check: Can user_id access board_id? (Read/Write check).
  • Input Sanitization:
    • Text inputs on whiteboards are risky. We must sanitize all text on the server (strip <script> tags) to prevent XSS attacks that could hijack other users' sessions.
  • Rate Limiting:
    • Limit the number of objects a user can create per minute. This prevents a malicious script from creating 100,000 rectangles and crashing the board for everyone.

14. Bottlenecks and next steps

  • Bottleneck: Initial Board Load. Loading a board with 50,000 objects takes time to parse and render.
    • Next Step: Implement Tiled Rendering. The server generates PNG image tiles of the board at different zoom levels (like Google Maps). The client loads these images first for instant visuals, then loads the interactive vector data in the background.
  • Bottleneck: Conflict Resolution. "Last Write Wins" is simple but can be annoying (User A overwrites User B's text).
    • Next Step: Implement CRDTs (Conflict-free Replicated Data Types) like Y.js. This allows multiple users to type in the same text box without overwriting each other, similar to Google Docs.

Summary

  1. Stateful WebSockets: The core engine holds board state in memory for low-latency broadcasting.

  2. Async Persistence: We use Kafka to buffer writes, ensuring the database doesn't slow down the live session.

  3. Optimistic UI: Clients update instantly to hide network latency.

  4. Viewport Optimization: We only sync data relevant to what the user is currently seeing to handle large scale.

Design Twitter Timeline
Design Google Docs
Mark as Completed

On this page

1. Problem Definition and Scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end to end

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary